package com.tbit.main.controller;

import com.tbit.main.common.JsonResult;
import com.tbit.common.constant.MethodEnum;
import com.tbit.common.constant.ModuleEnum;
import com.tbit.main.constant.OperateLog;
import com.tbit.main.pojo.AccountUser;
import com.tbit.main.pojo.DispatchConfig;
import com.tbit.main.service.DispatchConfigService;
import com.tbit.main.service.TokenService;
import com.tbit.main.util.Assert;
import com.tbit.main.util.DateTimeUtil;
import com.tbit.main.util.LogUtil;
import com.tbit.main.util.ObjectUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 调度配置
 *
 * @author LMY
 * @create 2020-10-27 11:20
 */
@RestController
@RequestMapping("/dispatchConfig")
public class DispatchConfigController {
    @Autowired
    private DispatchConfigService dispatchConfigService;
    @Autowired
    private TokenService tokenService;

    /**
     * 添加修改
     */
    @RequestMapping("/addAndUpdate")
    @OperateLog(module = ModuleEnum.DISPATCHCONFIG, methods = MethodEnum.DISPATCHCONFIG_ADD)
    public JsonResult<String> add(String token, DispatchConfig dispatchConfig) {
        Assert.notNull(dispatchConfig.getAccountId(), "AccountUser.agentId.notNull");

        AccountUser accountUser = tokenService.getAccount(token);

        DispatchConfig dispatchConfigContent = dispatchConfigService.getByAccountId(dispatchConfig.getAccountId());
        if (dispatchConfigContent == null) {
            dispatchConfig.nullToDefaultVal();
            dispatchConfig.setUpdateTime(DateTimeUtil.getNowTime());
            dispatchConfigService.insert(dispatchConfig);
        } else {
            dispatchConfig.setUpdateTime(DateTimeUtil.getNowTime());
            //替换可修改字段
            ObjectUtil.assign(dispatchConfig, dispatchConfigContent, null);
            dispatchConfigService.update(dispatchConfigContent);
        }
        LogUtil.info("修改调度配置,人员：" + accountUser.getAccountUserId() + ",配置：" + dispatchConfig.toString());
        return JsonResult.succ();
    }

    /**
     * 根据平台账号id查询
     */
    @RequestMapping("/getByAccountId")
    public JsonResult<DispatchConfig> getByAccountId(String token, Integer accountId) {
        Assert.notNull(accountId, "AccountUser,agentId.notNull");
        DispatchConfig diapatchConfig = dispatchConfigService.getByAccountId(accountId);
        if (diapatchConfig == null) {
            diapatchConfig = new DispatchConfig(accountId);
        }
        return JsonResult.succ(diapatchConfig);
    }

}
